import React, { useState, useEffect, useRef } from 'react';
import { View, Text, ScrollView, StyleSheet, TouchableOpacity } from 'react-native';
import { Toast, Flex } from "@ant-design/react-native";
import FcModal from '@/components/FcModal';

type Props = {
  isOpen?: boolean,
  titleText?: string,
  dateType?: string,
  dateValue?: string,
  dateRange?: Array<string>,
  onClose?: Function,
  onConfirm?: Function,
}
const DatePicker = ({isOpen, titleText, dateType, dateValue, dateRange, onClose, onConfirm}: Props) => {
  const [selectedStartDate, setSelectedStartDate] = useState<any>(null);
  const [selectedEndDate, setSelectedEndDate] = useState<any>(null);
  const [selectedYear, setSelectedYear] = useState<any>(null);
  const [selectedMonth, setSelectedMonth] = useState<any>(null);
  const [selectedDay, setSelectedDay] = useState<any>(null);
  const [dateTab, setDateTab] = useState<any>('start');
  const [dayList, setDayList] = useState<any>(Array.from({ length: 31 }, (_, i) => i + 1));

  const yearList = Array.from({ length: 100 }, (_, i) => 2000 + i);
  const monthList = Array.from({ length: 12 }, (_, i) => i + 1);

  const yearRef = useRef<any>(null);
  const monthRef = useRef<any>(null);
  const dayRef = useRef<any>(null);

  useEffect(() => {
    if(!isOpen){
      setDateTab('start')
      setSelectedStartDate('')
      setSelectedEndDate('')

      return
    }

    let date:any = null

    if(dateType == 'range'){
      date = dateRange?.[0] ? new Date(dateRange?.[0]) : new Date()
      setSelectedStartDate(`${date.getFullYear()}-${date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1}-${date.getDate() < 10 ? '0' + date.getDate() : date.getDate()}`)

      if(dateRange?.[1]){
        let date2 = new Date(dateRange?.[1])
        setSelectedEndDate(`${date2.getFullYear()}-${date2.getMonth() + 1 < 10 ? '0' + (date2.getMonth() + 1) : date2.getMonth() + 1}-${date2.getDate() < 10 ? '0' + date2.getDate() : date2.getDate()}`)
      }
    }else{
      date = dateValue ? new Date(dateValue) : new Date()
    }

    setTimeout(() => {
      handleScrollEnd('year', date.getFullYear())
      handleScrollEnd('month', date.getMonth() + 1)
      handleScrollEnd('day', date.getDate())
    }, 200)

  }, [isOpen]);

  //日期范围Tab
  const handleCheckTab = (val:any) => {
    if(dateTab != val){
      setDateTab(val)

      let date:any = null

      if(val == 'start'){
        date = selectedStartDate ? new Date(selectedStartDate) : new Date()
      }else if(val == 'end'){
        date = selectedEndDate ? new Date(selectedEndDate) : new Date()
        setSelectedEndDate(`${date.getFullYear()}-${date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1}-${date.getDate() < 10 ? '0' + date.getDate() : date.getDate()}`)
      }

      setTimeout(() => {
        handleScrollEnd('year', date.getFullYear())
        handleScrollEnd('month', date.getMonth() + 1)
        handleScrollEnd('day', date.getDate())
      }, 200)
    }
  }

  //滚动
  const handleScroll = (e:any, type:any) => {
    let index = Math.round(e.nativeEvent.contentOffset.y / 48)
    let str = ''

    if(type === 'year'){
      str = `${yearList[index]}-${selectedMonth < 10 ? '0' + selectedMonth : selectedMonth}-${selectedDay < 10 ? '0' + selectedDay : selectedDay}`
      setSelectedYear(yearList[index])
    }else if(type == 'month'){
      str = `${selectedYear}-${monthList[index] < 10 ? '0' + monthList[index] : monthList[index]}-${selectedDay < 10 ? '0' + selectedDay : selectedDay}`
      setSelectedMonth(monthList[index])
      setDayList(Array.from({ length: new Date(selectedYear, selectedMonth, 0).getDate() }, (_, i) => i + 1));
    }else{
      str = `${selectedYear}-${selectedMonth < 10 ? '0' + selectedMonth : selectedMonth}-${dayList[index] < 10 ? '0' + dayList[index] : dayList[index]}`
      setSelectedDay(dayList[index])
    }

    if(dateTab == 'start'){
      setSelectedStartDate(str)
    }else{
      setSelectedEndDate(str)
    }
  }

  //滚动结束
  const handleScrollEnd = (type:any, val:any) => {
    if(type === 'year'){
      let index = yearList.indexOf(val);
      yearRef.current?.scrollTo({ y: index * 48, animated: true });
      setSelectedYear(val)
    }else if(type == 'month'){
      let index = monthList.indexOf(val);
      monthRef.current?.scrollTo({ y: index * 48, animated: true });
      setSelectedMonth(val)
    }else{
      let index = dayList.indexOf(val);
      dayRef.current?.scrollTo({ y: index * 48, animated: true });
      setSelectedDay(val)
    }
  }
  
  //关闭
  const handleClose = () => {
    onClose?.(false)
  }

  //确认
  const handleConfirm = () => {
    if(dateType == 'range'){
      if(!selectedStartDate || !selectedEndDate){
        Toast.show('请选择日期');
        return
      }

      onConfirm?.(selectedStartDate, selectedEndDate);
    }else{
      let date = `${selectedYear}-${selectedMonth < 10 ? '0' + (selectedMonth + 1) : selectedMonth}-${selectedDay ? '0' + selectedDay : selectedDay}`
      onConfirm?.(date);
    }
    handleClose();
  }

  return (
    <FcModal
      style={{height: 400}}
      isOpen={isOpen}
      onFcModalClose={() => handleClose()}
      titleText={titleText}
      titleBottomBorderWidth={1}
      titleRight={
        <TouchableOpacity onPress={() => handleConfirm()}>
          <Text style={styles.title_right}>确认</Text>
        </TouchableOpacity>
      }
    >
      {
        dateType == 'range' ?
        <Flex justify='between' style={{paddingHorizontal: 16, height: 56}}>
          <TouchableOpacity style={[styles.date_tab, dateTab == 'start' && styles.date_tab_active]} onPress={() => handleCheckTab('start')}>
            <Flex justify='center' style={{flex: 1}}>
              <Text style={dateTab == 'start' && {color: '#2856FF'}}>{selectedStartDate || '开始日期'}</Text>
            </Flex>
          </TouchableOpacity>
          <Text style={{color: '#D8D8D8', fontSize: 25}}>-</Text>
          <TouchableOpacity style={[styles.date_tab, dateTab == 'end' && styles.date_tab_active]} onPress={() => handleCheckTab('end')}>
            <Flex justify='center' style={{flex: 1}}>
              <Text style={dateTab == 'end' && {color: '#2856FF'}}>{selectedEndDate || '结束日期'}</Text>
            </Flex>
          </TouchableOpacity>
        </Flex>
        : null
      }
      <View>
        {/* 选中区域 */}
        <View style={styles.indicator} />
        <Flex>
          {/* 年份列表 */}
          <ScrollView
            ref={yearRef}
            style={styles.scrollContainer}
            contentContainerStyle={styles.contentContainer}
            showsVerticalScrollIndicator={false}
            onScroll={(e) => handleScroll(e, 'year')}
            onMomentumScrollEnd={() => handleScrollEnd('year', selectedYear)}
          >
            {yearList.map((year) => (
              <View key={year} style={styles.dateItem}>
                <Text style={selectedYear === year ? styles.selectedDateItem : styles.unselectedDateItem}>{year}年</Text>
              </View>
            ))}
          </ScrollView>

          {/* 月份列表 */}
          <ScrollView
            ref={monthRef}
            style={styles.scrollContainer}
            contentContainerStyle={styles.contentContainer}
            showsVerticalScrollIndicator={false}
            onScroll={(e) => handleScroll(e, 'month')}
            onMomentumScrollEnd={() => handleScrollEnd('month', selectedMonth)}
          >
            {monthList.map((month) => (
              <View key={month} style={styles.dateItem}>
                <Text style={selectedMonth === month ? styles.selectedDateItem : styles.unselectedDateItem}>{month}月</Text>
              </View>
            ))}
          </ScrollView>

          {/* 日期列表 */}
          <ScrollView
            ref={dayRef}
            style={styles.scrollContainer}
            contentContainerStyle={styles.contentContainer}
            showsVerticalScrollIndicator={false}
            onScroll={(e) => handleScroll(e, 'day')}
            onMomentumScrollEnd={() => handleScrollEnd('day', selectedDay)}
          >
            {dayList.map((day:any) => (
              <View key={day} style={styles.dateItem}>
                <Text style={selectedDay === day ? styles.selectedDateItem : styles.unselectedDateItem}>{day}日</Text>
              </View>
            ))}
          </ScrollView>
        </Flex>
      </View>
    </FcModal>
  );
};

const styles = StyleSheet.create({
  title_right: {
    color: '#2856FF',
    fontSize: 15,
    lineHeight: 56,
  },
  date_tab: {
    width: '45%',
    height: 32,
    borderRadius: 30,
    backgroundColor: '#F1F2F4',
  },
  date_tab_active: {
    borderWidth: 1,
    borderColor: '#2856FF',
    backgroundColor: 'rgba(40, 86, 255, 0.1)',
  },
  indicator: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: '50%',
    transform: [{ translateY: -24 }],
    height: 48,
    borderTopWidth: 0.5,
    borderBottomWidth: 0.5,
    borderColor: 'rgba(0, 0, 0, 0.2)',
  },
  scrollContainer: {
    height: 300,
    overflow: 'hidden',
  },
  contentContainer: {
    paddingTop: 125,
    paddingBottom: 125,
  },
  dateItem: {
    height: 48,
    justifyContent: 'center',
    alignItems: 'center',
  },
  selectedDateItem: {
    color: '#000',
  },
  unselectedDateItem: {
    color: 'rgba(0, 0, 0, 0.3)',
  },
});

export default DatePicker;